package com.example.server.transport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.server.trasaction.HaeTransactionManager;
import com.example.server.trasaction.HaeTransactionModel;
import com.example.server.trasaction.TransactionType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @Auther: yuanjianpeng
 * @Date: 2019/5/18 12:03
 * @Description:
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext channelHandlerContext;

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channelHandlerContext = ctx;
    }

    //接受返回数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接收数据：" + msg.toString());
        JSONObject jsonObject = JSON.parseObject((String) msg);

        String groupId = jsonObject.getString("groupId");
        String command = jsonObject.getString("command");
        System.out.println("接收command:" + command);
        //对事务对象进行操作
        HaeTransactionModel haeTransactionModel = HaeTransactionManager.getByGroupId(groupId);
        if ("commit".equals(command)) {
            haeTransactionModel.setTransactionType(TransactionType.commit);
        } else {
            haeTransactionModel.setTransactionType(TransactionType.rollback);
        }
        haeTransactionModel.getTask().signalTask();
    }

    //发送数据
    public synchronized Object call(JSONObject data) {
        channelHandlerContext.writeAndFlush(data.toJSONString());
        return null;
    }
}
